import PopupDate from "@/components/PopupDate"
import s from "./style.module.less"
import { useEffect, useRef, useState } from "react"
import dayjs from "dayjs"
import { getDataApi } from "@/apis"
import classNames from "classnames"
import IconFont from "@/components/CustomIcon"
import { typeMap } from "@/utils"
import { ProgressBar } from "antd-mobile"
import * as echarts from "echarts"

let myChart = null

function Data() {
  const monthRef = useRef()
  const [currentMonth, setCurrentMonth] = useState(dayjs().format("YYYY-MM")) //当前选择的日期
  const [totalType, setTotalType] = useState("expense") // 收入或支出类型
  const [totalExpense, setTotalExpense] = useState(0) // 总支出
  const [totalIncome, setTotalIncome] = useState(0) // 总收入
  const [expenseData, setExpenseData] = useState([]) // 支出数据
  const [incomeData, setIncomeData] = useState([]) // 收入数据
  const [pieType, setPieType] = useState("expense") // 饼图的「收入」和「支出」控制

  const changeTotalType = (val) => {
    setTotalType(val)
  }

  useEffect(() => {
    getData()
  }, [currentMonth])

  const getData = async () => {
    let { data } = await getDataApi(currentMonth)
    data = data.data

    // 总收支
    setTotalExpense(data.total_expense)
    setTotalIncome(data.total_income)

    // 过滤支出和收入
    const expense_data = data.total_data
      .filter((item) => item.pay_type == 1)
      .sort((a, b) => b.number - a.number) // 过滤出账单类型为支出的项
    const income_data = data.total_data
      .filter((item) => item.pay_type == 2)
      .sort((a, b) => b.number - a.number) // 过滤出账单类型为收入的项
    setExpenseData(expense_data)
    setIncomeData(income_data)

    // 绘制饼图
    setPieChart(pieType == "expense" ? expense_data : income_data)
  }

  const setPieChart = (data) => {
    if (data.length === 0) return

    let chartDom = document.getElementById("proportion")
    myChart = echarts.init(chartDom)
    let option = {
      tooltip: {
        trigger: "item",
        formatter: "{a} <br/>{b} : {c} ({d}%)",
      },
      // 图例
      legend: {
        data: data.map((item) => item.type_name),
      },
      series: [
        {
          name: "支出",
          type: "pie",
          radius: "55%",
          data: data.map((item) => {
            return {
              value: item.number,
              name: item.type_name,
            }
          }),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
      ],
    }
    option && myChart.setOption(option)
  }

  const monthShow = () => {
    monthRef.current && monthRef.current.showP()
  }

  const selectMonth = (item) => {
    setCurrentMonth(item)
  }

  const changePieType = (type) => {
    setPieType(type)
    setPieChart(type === "expense" ? expenseData : incomeData)
  }
  return (
    <div className={s.data}>
      <div className={s.total}>
        <div className={s.time} onClick={monthShow}>
          <span>{currentMonth}</span>
        </div>
        <div className={s.title}>共支出</div>
        <div className={s.expense}>¥{Number(totalExpense).toFixed(2)}</div>
        <div className={s.income}>共收入¥{Number(totalIncome).toFixed(2)}</div>
      </div>
      <div className={s.structure}>
        <div className={s.head}>
          <span>收支构成</span>
          <div className={s.tab}>
            <span
              className={totalType === "expense" ? s.expense : undefined}
              onClick={() => changeTotalType("expense")}
            >
              支出
            </span>
            <span
              className={totalType === "income" ? s.income : undefined}
              onClick={() => changeTotalType("income")}
            >
              收入
            </span>
          </div>
        </div>
        <div className={s.content}>
          {(totalType === "expense" ? expenseData : incomeData).map((item) => (
            <div key={item.type_id} className={s.item}>
              <div className={s.left}>
                <div className={s.type}>
                  <span
                    className={classNames({
                      [s.expense]: totalType == "expense",
                      [s.income]: totalType == "income",
                    })}
                  >
                    <IconFont
                      type={item.type_id ? typeMap[item.type_id].icon : 1}
                    />
                  </span>
                  <span className={s.name}>{item.type_name}</span>
                </div>
                <div className={s.progress}>
                  ¥{Number(item.number).toFixed(2) || 0}
                </div>
              </div>
              <div className={s.right}>
                <div className={s.percent}>
                  <ProgressBar
                    percent={Number(
                      (item.number /
                        Number(
                          totalType == "expense" ? totalExpense : totalIncome
                        )) *
                        100
                    ).toFixed(2)}
                    style={{
                      "--track-color": "#fff",
                    }}
                    text
                  />
                </div>
              </div>
            </div>
          ))}
        </div>
        <div className={s.proportion}>
          <div className={s.head}>
            <span>收支构成</span>
            <div className={s.tab}>
              <span
                className={pieType === "expense" ? s.expense : undefined}
                onClick={() => changePieType("expense")}
              >
                支出
              </span>
              <span
                className={pieType === "income" ? s.income : undefined}
                onClick={() => changePieType("income")}
              >
                收入
              </span>
            </div>
          </div>
          <div id="proportion" style={{ width: "100%", height: "576px" }}></div>
        </div>
      </div>
      <PopupDate ref={monthRef} mode="month" onSelect={selectMonth}></PopupDate>
    </div>
  )
}

export default Data
